package com.aimei520.controller;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aimei520.po.admin.Role;
import com.aimei520.po.admin.Url;
import com.aimei520.po.admin.User;
import com.aimei520.service.api.AdminService;
import com.aimei520.utils.JsonResult;
import com.aimei520.utils.NavListUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/admin")
public class AdminController{
	
	@Resource
	private AdminService adminService;
	
	private int getPageNum(String pageNum) {
		try {
			if(Integer.parseInt(pageNum) > 0 ) {
				return Integer.parseInt(pageNum);
			}
		}catch(Exception e) {
			
		}
		return 1;
	}
	
	/**
	 * 用于将传入的urlid字符串转成int数组
	 * @return
	 */
	private int[] string2IntArray(String urlid) {
		if("".equals(urlid)){
			return new int[1];
		}
		String[] strArray = urlid.split(",");
		int[] urlids = new int[strArray.length];
		for (int i = 0; i < strArray.length; i++) {
			urlids[i] = Integer.parseInt(strArray[i]);
		}
		return urlids;
	}
	
	/**
	 * 角色列表
	 * @param model
	 * @param pageNum
	 * @param request
	 * @return 视图
	 */
	@RequestMapping("/rolelist")
	public String roleList(Model model,String pageNum, HttpServletRequest request) {
	
		PageHelper.startPage(getPageNum(pageNum), 15, true);
		List<Role> role = adminService.roleList(new Role());
		PageInfo<Role> roles = new PageInfo<Role>(role);
		
		model.addAttribute("roles",roles);
		model.addAttribute(
				"page",
				NavListUtils.getNavList(
						request.getContextPath()+request.getServletPath(),getPageNum(pageNum), roles.getNavigatepageNums(), roles.isIsFirstPage(), roles.isIsLastPage()
					)
				);
		return "admin/roleList";
	}
	
	/**
	 * 角色编辑视图
	 * @param model
	 * @param request
	 * @param role
	 * @return 角色编辑视图
	 */
	@RequestMapping(value ="/roleedit",method=RequestMethod.GET)
	public String  roleEdit(Model model, HttpServletRequest request,Role role) {
		
		Role role_byId = adminService.roleList(role).get(0);
		
		model.addAttribute("role",role_byId);
		
		model.addAttribute("urls",adminService.urlList(role.getId()));
		
		
		return "admin/roleEdit";
	}
	
	/**
	 * 角色编辑方法
	 * @param model
	 * @param request
	 * @param urlid
	 * @param role
	 * @return 返回结果
	 */
	@ResponseBody
	@RequestMapping(value ="/roleedit",method=RequestMethod.POST)
	public JsonResult  roleEdit(Model model, HttpServletRequest request,String urlid,Role role) {
		
		int[] urlids = string2IntArray(urlid);
		
		adminService.updateRoleAccess(role, urlids);
		
		JsonResult jsonResult = new JsonResult();
		jsonResult.setSuccess(true);
		jsonResult.setMsg("成功");
		
		return jsonResult;
	}
	

	
	@RequestMapping(value="/roleadd", method=RequestMethod.GET)
	public String  roleAdd(Model model, HttpServletRequest request) {
		model.addAttribute("urls",adminService.urlList(0));
		return "admin/roleAdd";
	}
	
	@ResponseBody
	@RequestMapping(value="/roleadd", method=RequestMethod.POST)
	public JsonResult  roleAdd(Model model, HttpServletRequest request,String urlid,Role role) {
		JsonResult result = new JsonResult(true,"添加成功");
		int[] urlids = string2IntArray(urlid);
		
		adminService.addRole(role, urlids);
		
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value ="/roledelete",method=RequestMethod.POST)
	public JsonResult roleDelete(Role role) {
		JsonResult result = new JsonResult(true,"删除成功！");
		
		adminService.deleteRole(role);
		
		return result;
	}
	
	
	
	/**
	 * 权限列表
	 * @param model
	 * @param pageNum
	 * @param request
	 * @return 返回视图
	 */
	@RequestMapping("/urllist")
	public String urlList(Model model,String pageNum, HttpServletRequest request) {
		
		PageHelper.startPage(getPageNum(pageNum), 15, true);
		Url urlQueryVo = new Url();
		urlQueryVo.setStatus(1);
		List<Url> url = adminService.urlList(urlQueryVo);
		PageInfo<Url> urls = new PageInfo<Url>(url);
		
		model.addAttribute("urls",urls);
		model.addAttribute(
				"page",
				NavListUtils.getNavList(
						request.getContextPath()+request.getServletPath(),getPageNum(pageNum), urls.getNavigatepageNums(), urls.isIsFirstPage(), urls.isIsLastPage()
					)
				);
		model.addAttribute("headUrls",adminService.headUrlList());
		return "admin/urlList";
	}
	
	/**
	 * 添加权限方法
	 * @param url
	 * @return 添加结果
	 */
	@ResponseBody
	@RequestMapping(value ="/urladd",method=RequestMethod.POST)
	public JsonResult addUrl(Url url) {
		JsonResult result = new JsonResult(true,"添加成功！");
		
		url.setStatus(1);
		adminService.addUrl(url);
		
		return result;
	}
	
	/**
	 * 返回编辑权限视图
	 * @param model
	 * @return
	 */
	@RequestMapping(value ="/urledit",method=RequestMethod.GET)
	public String editUrl(Model model,Url url) {
		
		model.addAttribute("headUrls",adminService.headUrlList());
		model.addAttribute("self",adminService.urlList(url).get(0));
		
		return "admin/urlEdit";
	}
	
	/**
	 * 修改权限的方法
	 * @param url
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value ="/urledit",method=RequestMethod.POST)
	public JsonResult editUrl(Url url) {
		JsonResult result = new JsonResult(true,"添加成功！");
		adminService.updateUrl(url);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value ="/urldelete",method=RequestMethod.POST)
	public JsonResult urlDelete(Url url) {
		JsonResult result = new JsonResult(true,"删除成功！");
		url.setStatus(2);
		adminService.updateUrl(url);
		return result;
	}
	
	/*******************用户控制***********************/
	
	@RequestMapping("/userlist")
	public String userList(Model model, String pageNum, HttpServletRequest request) {
		
		PageHelper.startPage(getPageNum(pageNum), 15, true);
		List<User> user = adminService.userList(new User());
		PageInfo<User> users = new PageInfo<User>(user);
		
		model.addAttribute(
				"page",
				NavListUtils.getNavList(
						request.getContextPath()+request.getServletPath(),getPageNum(pageNum), users.getNavigatepageNums(), users.isIsFirstPage(), users.isIsLastPage()
					)
				);
		model.addAttribute("users",users);
		return "admin/userList";
	}
	
	@RequestMapping(value="/useradd",method=RequestMethod.GET)
	public String userAdd(Model model,User user) {
		Role role = new Role();
		role.setStatus(1);
		model.addAttribute("role",adminService.roleList(role));
		return "admin/userAdd";
	}
	
	@ResponseBody
	@RequestMapping(value="/useradd",method=RequestMethod.POST)
	public JsonResult userAdd(User user) {
		JsonResult result = new JsonResult(true, "添加成功");
		
		user.setStatus(1);
		user.setCreatetime(new Date());
		try {
			adminService.addUser(user);
		} catch (NoSuchAlgorithmException e) {
			result.setMsg("添加失败");
			result.setSuccess(false);
		}
		
		return result;
	}
	
	@RequestMapping(value="/useredit", method=RequestMethod.GET)
	public String userEdit(Model model,User user) {
		
		model.addAttribute("user", adminService.user_byId(user.getId()));
		
		Role role = new Role();
		role.setStatus(1);
		model.addAttribute("role",adminService.roleList(role));
		
		return "admin/userEdit";
	}
	
	
	@ResponseBody
	@RequestMapping(value="/useredit",method=RequestMethod.POST)
	public JsonResult userEdit(User user) throws NoSuchAlgorithmException {
		JsonResult result = new JsonResult(true, "编辑成功");
		
		adminService.updateUser(user);	
		
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/userdelete",method=RequestMethod.POST)
	public JsonResult userDelete(User user) {
		JsonResult result = new JsonResult(true, "编辑成功");
		
		adminService.deleteUser(user.getId());	
		
		return result;
	}
}
